import os

from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.ext.webapp import template

from ixapi.db import SimpleListDB, FilesDB, PhoneSpyDB

from auth import SECRET

def simpleList(self):
  listDb = SimpleListDB.all().order('-created')
  view_list = os.path.join(os.path.dirname(__file__), 'view/api/SimpleList.xml')
  view_list_values = {
    'lists': listDb,
    }
  self.response.headers['Content-Type'] = "application/xml"
  self.response.out.write(template.render(view_list, view_list_values))

def simpleListAdd(self):
  s = self.request.get('secret')
  if(s == SECRET):
    listDb = SimpleListDB()
    listDb.title = self.request.get('title')
    listDb.put()
    self.response.out.write('Done!')
  else:
    self.response.out.write('ERROR!')
    

def fileList(self):
  siteDomain = 'http://' + self.request.headers['Host']
  listDb = FilesDB.all().order('-created')
  view_list = os.path.join(os.path.dirname(__file__), 'view/api/FileList.xml')
  view_list_values = {
    'siteDomain' : siteDomain,
    'lists': listDb,
    }
  self.response.headers['Content-Type'] = "application/xml"
  self.response.out.write(template.render(view_list, view_list_values))
  
def phonespy(self):
  spyDB = PhoneSpyDB()
  spyDB.name = self.request.get('name')
  spyDB.subject = self.request.get('subject')
  spyDB.content = self.request.get('content')
  spyDB.put()
  self.response.out.write('Done!')

class MainHandler(webapp.RequestHandler):

  def get(self):
    mainview = os.path.join(os.path.dirname(__file__), 'view/api/Main.htm')
    mainview_list = {}
    self.response.out.write(template.render(mainview, mainview_list))
    
  def post(self):
    method = self.request.get('method')
    
    methodList = {
      "simpleList" : simpleList,
      "simpleListAdd" : simpleListAdd,
      "fileList" : fileList
    }
    
    try:
      methodList[method](self)
    except KeyError:
      self.response.out.write('KeyError!')
    
class SimpleList(webapp.RequestHandler):
  def get(self):
    simpleList(self)

class FileList(webapp.RequestHandler):
  def get(self):
    fileList(self)

class PhoneSpy(webapp.RequestHandler):
  def get(self):
    phonespy(self)

def main():
  application = webapp.WSGIApplication([('/a', MainHandler),
                                        ('/a/', MainHandler),
                                        ('/a/simplelist', SimpleList),
                                        ('/a/filelist', FileList),
                                        ('/a/phonespy', PhoneSpy)
                                        ],
                                       debug=True)
  util.run_wsgi_app(application)

if __name__ == '__main__':
  main()
